<template>
  <div class="app-container">
    <div class="form-container">
          <el-form ref="searchForm" :model="searchForm" label-width="80px">
            <el-row :gutter="20">
                <el-col :span="5">
                    <el-form-item label="产品类型" prop="productId">
                      <el-select v-model="searchForm.productId" 
                        clearable filterable placeholder="请选择产品类型" >
                          <el-option
                            v-for="item in products"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                            <span style="float: left">{{ 'ID: ' + item.id }}</span>
                            <span style="float: right;  font-size: 14px">{{ item.name }}</span>
                          </el-option>
                      </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="客户类型" prop="levelId">
                      <el-select v-model="searchForm.levelId" 
                        clearable filterable placeholder="请选择客户类型" >
                          <el-option
                            v-for="item in levels"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                            <span style="float: left">{{ 'ID: ' + item.id }}</span>
                            <span style="float: right;  font-size: 14px">{{ item.name }}</span>
                          </el-option>
                      </el-select>
                    </el-form-item>
                </el-col>
                  <el-col :span="10">
                      <el-form-item  label="时间范围" prop="time">
                            <el-date-picker
                                v-model="searchForm.time"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                            </el-date-picker>
                      </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-button icon="el-icon-search" type="primary" circle @click="getData" />
                  <el-button icon="el-icon-refresh-right" type="warning" size="medium" round @click="resetForm('searchForm')">
                      重置
                    </el-button>
              </el-col>
            </el-row>
        </el-form>
    </div>
    
       <div class="action">
        <el-switch  v-model="show" 
            active-color="#13ce66" inactive-color="#ff4949" 
            active-text="显示表格" inactive-text="显示图标"/>
            <span style="margin-left: 10px;">{{'总金额: '+ sum}}</span>
    </div>
    <!-- 表格 -->
    <div v-show="show">
       <el-table stripe border fit highlight-current-row
    :header-cell-style="{textAlign: 'center'}"
     :cell-style="{ textAlign: 'center' }"
    :data="orders.slice((page - 1) * limit, page * limit)" style="width: 100%">
    
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="table-expand">
            <el-form-item label="客户ID">
              <span>{{ props.row.student.id }}</span>
            </el-form-item>
            <el-form-item label="创建人ID">
              <span>{{ props.row.admin.id }}</span>
            </el-form-item>
            <el-form-item label="客户姓名">
              <span>{{ props.row.student.username }}</span>
            </el-form-item>
            <el-form-item label="创建人姓名">
              <span>{{ props.row.admin.username }}</span>
            </el-form-item>
            <el-form-item label="客户性别">
              <span>{{ props.row.student.sex == 0 ? '男': '女' }}</span>
            </el-form-item>
            <el-form-item label="创建人性别">
              <span>{{ props.row.admin.sex == 0 ? '男': '女'}}</span>
            </el-form-item>
            <el-form-item label="客户生日">
              <span>{{ $dayjs(props.row.student.birth).format('YYYY-MM-DD') }}</span>
            </el-form-item>
            <el-form-item label="创建人生日">
              <span>{{ $dayjs(props.row.admin.birth).format('YYYY-MM-DD') }}</span>
            </el-form-item>
            <el-form-item label="客户专业">
              <span>{{ props.row.student.username }}</span>
            </el-form-item>
            <el-form-item label="创建人邮箱">
              <span>{{ props.row.admin.email }}</span>
            </el-form-item>
            <el-form-item label="客户类型">
              <span>{{ props.row.student.level.name }}</span>
            </el-form-item>
            <el-form-item label="创建人类型">
              <span>{{ props.row.admin.role.name }}</span>
            </el-form-item>
            <el-form-item label="客户手机号">
              <span>{{ props.row.student.phoneNum }}</span>
            </el-form-item>
              <el-form-item label="创建人手机">
              <span>{{ props.row.admin.phoneNum }}</span>
            </el-form-item>
            <el-form-item label="客户状态">
              <span>{{ props.row.student.isEnable == 0 ? '禁用': '正常' }}</span>
            </el-form-item>
            <el-form-item label="创建人状态">
              <span>{{ props.row.admin.isEnable == 0 ? '禁用': '正常'}}</span>
            </el-form-item>
            <el-form-item label="客户地址">
              <span>{{ props.row.student.address }}</span>
            </el-form-item>
            <el-form-item label="创建人地址">
              <span>{{ props.row.admin.address }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column label="ID" prop="id" width="80"/>
      <el-table-column label="业务名称" prop="product.name"/>
      <el-table-column label="缴费人" prop="student.username"/>
      <el-table-column label="缴费类型" prop="student.level.name"/>

      <el-table-column label="创建时间" prop="createTime" min-width="90">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 5px">{{ $dayjs(scope.row.createTime).format('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最近缴费时间" prop="renewTime" min-width="90">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 5px">{{ $dayjs(scope.row.renewTime).format('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="到期时间" prop="endTime" min-width="90">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 5px">{{ $dayjs(scope.row.endTime).format('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" prop="isEnable"  label="状态" width="100">
          <template slot-scope="{row}">
            <el-tag :type="row.endTime | statusFilter(that)">
              {{ formatterStatus(row.endTime)}}
            </el-tag>
          </template>
        </el-table-column>

      <el-table-column label="总费用 (元)" prop="totalMoney"/>
      <el-table-column label="经办人" prop="admin.username"/>

      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="page" :limit.sync="limit" @pagination="getData"/>
    </div>
   <!--图标  -->
    <div class="main" v-show="!show">
      <div class="temp">
        <div id="order" style="height: 100%; -webkit-tap-highlight-color: transparent; user-select: none;" ></div>
      </div>
    </div>
 
  </div>
   
</template>


<script>

import Pagination from "@/components/Pagination";
export default {
  components: { Pagination },
    filters: {
    statusFilter(endTime,that) {
      const statusMap = { 0: 'danger', 1: 'success',2:'warning'}
      let status
      if(that.nowTime.getTime() - endTime > 0 )  {
          status = 0
      }else if((endTime - that.nowTime.getTime())/(1000*60*60*24) <= 7){
          status = 2
      }else{
          status = 1
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      levels: [],
      products:[],
      option: {
          legend: {
              top: 'bottom'
          },
          toolbox: {
              show: true,
              feature: {
                  mark: {show: true},
                  dataView: {show: true, readOnly: false},
                  restore: {show: true},
                  saveAsImage: {show: true}
              }
          },
          series: [
              {
                  name: '面积模式',
                  type: 'pie',
                  radius: [100, 250],
                  center: ['50%', '50%'],
                  roseType: 'area',
                  itemStyle: {
                      borderRadius: 20
                  },

                  data: [
                      // {value: 40, name: '产品1'},
                      // {value: 38, name: '产品2'},
                      // {value: 32, name: '产品3'},
                      // {value: 30, name: '产品4'},
                      // {value: 28, name: '产品5'},
                      // {value: 26, name: '产品6'},
                      // {value: 22, name: '产品7'},
                      // {value: 18, name: '产品8'}
                  ]
              }
          ]
      },
      page: 1,
      limit: 5,
      total: 0,
      show:false,
      orders:[],
      searchForm: {
        productId:'',
        levelId: '',
        time:[],
      },
      datas:[],
      nowTime:'',
      that:this, 
      sum:0 // 表格总金额
    };
  },
  methods: {
      async getData() {  
        this.nowTime = new Date()
        // 请求数据
        // this.option.series[0].data = []
        // 获取客户类型列表
        let res = await this.$store.dispatch('dataBase/getLevelList') 
        if(res.code == 1) {
            // console.log(res.data);
            this.levels = res.data
        }else{
            this.$message({ showClose: true,message: res.msg, type: 'error'})
        }

          // 获取产品列表
        res = await this.$store.dispatch('dataBase/getProductList') 
        if(res.code == 1) {
            this.products = res.data
        }else{
            this.$message({ showClose: true,message: res.msg, type: 'error'})
        }

        res = await this.$store.dispatch('order/orderChart',this.searchForm) 

          if(res.code == 1) {
              this.orders = res.data 
                 this.total = this.orders.length 
          }else{
              this.$message({ showClose: true,message: res.msg, type: 'error'})
          }

          // // 统计
          this.initData()
      },
      initData() {
        // 统计数据
        this.countOrder()
          //初始化数据
        // 基于准备好的dom，初始化echarts实例
        //有的话就获取已有echarts实例的DOM节点。
      let myChart = this.$echarts.getInstanceByDom(document.getElementById("order"))
      if (myChart == null) { // 如果不存在，就进行初始化
          myChart =  this.$echarts.init(document.getElementById('order'));
      }
        // 绘制图表
        myChart.setOption(this.option);
      },
      countOrder() {
        // 先清除之前的数据
        this.option.series[0].data = []
        this.datas=[]
        this.sum = 0
        // 统计订单数据 合并相同的用户
        for(let i=0; i < this.orders.length; i++) {
              // 取出这个订单的 总金额 
              let totalMoney = this.orders[i].totalMoney
              // 获得对应学生的 id
              let id = this.orders[i].student.id
              let username = this.orders[i].student.username
              // 查询是否存在这个 id
              const index = this.datas.map(item => item.id).indexOf(id)
              if(index != -1) {
                  this.datas[index].totalMoney += totalMoney
              }else{
                this.datas.push({id,username,totalMoney})
              }
        }
        
        for(let i=0; i < this.datas.length; i++) {
            // 取出计算的各个人的总金额
            let num = this.datas[i].totalMoney
            // 计算总金额
            this.sum += num
            // 用 id 和姓名拼接成 名字 
            let name = "ID "+this.datas[i].id+" "+ this.datas[i].username +" 总花费 "+ this.datas[i].totalMoney
              
            this.option.series[0].data.push({value:num,name:name})
        }
        console.log(this.sum);
      },
      resetForm(searchForm) {
        this.$refs[searchForm].resetFields()
        this.$message({  message: '清空成功', type: 'success'})
      },
      formatterStatus(endTime) {
        let status
        if(this.nowTime.getTime() - endTime > 0 )  {
            status = '到期'
        }else if((endTime - this.nowTime.getTime())/(1000*60*60*24) <= 7){
            status = '即将到期'
        }else{
            status = '正常'
        }
       
      return status
    }
    },
    async mounted() {
      await this.getData()
    }
  }
  </script>

<style lang="scss" scoped>
  .form-container {
    display: flex;
    width: 100%;
    align-items:center;
    justify-content:center;
  }
  .search {
    width: 100%;
    text-align: center;
    padding-left: 20px;
  }
  .main{

    width: 100%;
    height: 100%
    
  }
  .temp{
    width: 600px;
    margin: 0 auto;
    height: 600px;
  }
    .action {
    width: 100%;
    padding-bottom: 10px;
    text-align: center;
  }
    .table-expand {
    font-size: 0;
  }
  .table-expand label {
    width: 90px;
  }
  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>







